<?php
namespace App\Services\Music\Music;

use App\Models\Files\Files;
use App\Models\Music\Music;
use App\Models\Music\MusicCheck;
use App\Models\Sp\Sp;
use App\Services\Office\Office;
use Illuminate\Support\Facades\DB;
use App\Models\Music\PdfFile;


class MusicLogic
{

    //领取音乐
    public function musicGetTask(){
        $music = Music::where('check_status', '=', 0)->orderBy('id','asc')->select('album_id')->limit(30)->get()->toArray();
        $b = 0;
        foreach($music as $k=>$v){
           $c = Music::where('album_id','=',$music[$k]['album_id'])->update(['check_status'=>1,'check_man'=>session('username')]);
           $b+=$c;
           if($b>=30){break;}
        }
        $res = Music::where('check_status','=',1)->where('check_man','=',session('username'))->get()->toArray();
        return auto_return($res,'成功！');
    }

    //列表
    public function musicList($data){
        //$library = !empty($data['library']) ? implode(',',$data['library']) : '';
        $library = !empty($data['library']) ? $data['library'] : '';
        $work_rate = !empty($data['work_rate']) ? $data['work_rate'] : '';
        if($data['type']==0) {
            $query = Music::with('music_file','accompaniment_file','mv_file','video_file','karaoke_file','music_check','users_info')->whereIn('check_status',[2,4]);
        }else{
            $query = $this->searchMusic($data);
        }
        !empty($data['title']) && $query->where('title', '=', $data['title']);
        !empty($data['album']) && $query->where('album', '=', $data['album']);
        !empty($data['performer']) && $query->where('performer', '=', $data['performer']);
        !empty($data['online_time']) && $query->where('online_time', '=', $data['online_time']);
        !empty($data['property']) && $query->where('property', '=', $data['property']);
        !empty($library) && $query->whereHas('music_check', function ($query) use ($library) {
            $query->whereIn('library',$library);
        });
        !empty($work_rate) && $query->whereHas('music_check', function ($query) use ($work_rate) {
            $query->where('work_rate', '=', $work_rate);
        });
        //dd($data);
        !empty($data['check_man']) && $query->where('check_man', '=', $data['check_man']);
        !empty($data['type_status']) && $query->whereHas('music_check', function ($query) {
            $query->where('type_status', '=', 1);
        });
        !empty($data['is_commond']) && $query->whereHas('music_check', function ($query) {
            $query->where('is_commond', '=', 2);
        });
        !empty($data['expired_time']) && $query->whereHas('users_info', function ($query) {
            $query->where('expired_time', '<', NOW);
        });

        if (!empty($data['expired_time3'])) {
            $nextmonth = strtotime("+3 months", strtotime("now"));
            $premonth = strtotime("-3 months", strtotime("now"));
            $query->whereHas('users_info', function ($query) use ($nextmonth, $premonth) {
                $query->where('expired_time', '<', $nextmonth)->where('expired_time', '>', $premonth);
            });
        }

        if (!empty($data['in_sp'])) {
            $in_sp = $data['in_sp'];
            $not_sp = $data['not_sp'];
            $arr1 = Music::whereHas('music_sp', function ($query) use ($in_sp, $not_sp) {
                $query->where(function ($query) use ($in_sp) {
                    $query->whereIn('sp_id', $in_sp)->where('status', '=', 1);
            });
            })->select('library_id')->distinct()->get()->toArray();
            foreach($arr1 as $v){
                $array1[]=$v['library_id'];
            }
            $arr2 = Music::whereHas('music_sp', function ($query) use ($in_sp, $not_sp) {
                $query->where(function ($query) use ($not_sp) {
                    $query->whereIn('sp_id', $not_sp)->where('status', '=', 0);
                });
            })->select('library_id')->distinct()->get()->toArray();
            foreach($arr2 as $v){
                $array2[]=$v['library_id'];
            }
            if(!empty($array1) && !empty($array2)) {
                $arr = array_intersect($array1, $array2);
                $query->whereIn('library_id', $arr);
            }else{
                $query->where('library_id','=',0);
            }
        }

        $res = $query->paginate(10);
        return auto_return($res,'成功！');
    }

    //搜索音乐
    public function searchMusic($data){
        if($data['type'] == 1) {
            //审核搜索音乐
            $query = Music::whereIn('check_status', [0,1]);
        }else{
            //作品上线
            $query = Music::with( 'users_info','user','music_check')->where('check_status', '=', 2)->where('type_status','=',0);
        }
        return $query;
    }

    //音乐详情
    public function musicDetail($data){
        $res = Music::with('music_file','accompaniment_file','mv_file','video_file','karaoke_file','users_info')->where('id','=',$data['id'])->get()->toArray();
        $image_size = getimagesize($res[0]['cover']);
        $res[0]['image_info'] = $image_size;
        return auto_return($res,'成功!');
    }

    //审核音乐
    public function checkMusic($data){
        $expired_time = strtotime("+15 day", strtotime(date("Y-m-d")));
       if(!empty($data['submit_single'])){
           $res = Music::where('id','=',$data['id'])->update(['check_status'=>3,'expired_time'=>$expired_time]);
       }else if(!empty($data['submit_albums'])){
           $res = Music::where('album_id','=',$data['album_id'])->update(['check_status'=>3,'expired_time'=>$expired_time]);
           $id = Music::where('album_id','=',$data['album_id'])->select('id')->get()->toArray();
           return auto_return(['id'=>$id],'操作成功');
       }else if(!empty($data['submit_pass'])){
           $check_time = date('Y-m-d');
           $res = Music::where('id', '=', $data['id'])->update(['check_status' => 2,'check_time'=>$check_time,'check_man'=>session('username')]);
           MusicCheck::insert(['music_id'=>$data['id'],'work_rate'=>$data['work_rate'],'style'=>$data['style'],'singer_type'=>$data['singer_type'],'language'=>$data['language'],'is_commond'=>$data['is_commond'] ?? 1,'library'=>$data['library'],'area'=>$data['area'],'speed'=>$data['speed'],'mood'=>$data['mood']]);
       }
       return auto_return(['id'=>$data['id']],'操作成功');
    }

    //统计音乐
    public function statisticsMusic(){
        $awaitCheck = Music::where('check_status','=',0)->count();
        $todayCheck = Music::where('check_time','=',date('Y-m-d'))->where('check_status','=',2)->count();
        $myCheck = Music::where('check_man','=',session('username'))->where('check_status','=',2)->count();
        $reiterateCheck = Music::where('check_man','=',session('username'))->where('check_status','=',3)->count();
        $beingCheck = Music::where('check_man','=',session('username'))->where('check_status','=',1)->count();
        $res = [$awaitCheck,$todayCheck,$myCheck,$reiterateCheck,$beingCheck];
        return auto_return($res,'返回成功');
    }

    //根据平台统计音乐
    public function musicBySp($data){
        if($data['type'] == 0) {
            //常规发布
            $res = Sp::where('status','=',1)->select('id', 'simple_name', 'cstatus', 'ystatus', 'bstatus', 'mstatus', 'kstatus', 'dstatus')->get()->toArray();
        }else{
            $music = Music::with('music_check')->where('type_status','=',$data['type'])->where('check_status','=',2)->get()->toArray();
            foreach($music as $v){
                $simple_name[]=$v['music_check']['first_sp'];
            }
            $res = Sp::whereIn('simple_name',$simple_name)->select('id', 'simple_name', 'cstatus', 'ystatus', 'bstatus', 'mstatus', 'kstatus', 'dstatus')->get()->toArray();
        }
        foreach($res as $k=>$v){
            if($data['type'] == 0) {
                //得到对应得文件
                $query = Music::where('check_status', '=', 2)->where('type_status', '=', $data['type'])->with('music_file', 'accompaniment_file', 'mv_file', 'video_file', 'karaoke_file', 'music_check')->whereHas('music_sp', function ($query) use ($v) {
                    $query->where('sp_id', '=', $v['id'])->where('status', '=', 1);
                });
                //筛选库
                if($data['library']!=1){
                    $library = json_decode($data['library']);
                    $query->whereHas('music_check', function ($query) use ($library) {
                        $query->whereIn('library',$library );
                    });
                }
                $query = $query->get()->toArray();
            }else{
                $query = Music::where('check_status', '=', 2)->where('type_status', '=', $data['type'])->with('music_file', 'accompaniment_file', 'mv_file', 'video_file', 'karaoke_file', 'music_check')->whereHas('music_check', function ($query) use ($v) {
                    $query->where('first_sp', '=', $v['simple_name']);
                })->get()->toArray();
            }
            $cstatus = 0;$ystatus = 0;$bstatus = 0;$mstatus = 0;$kstatus = 0;$dstatus = 0;
            foreach ($query as $q){
                if($v['cstatus']==0){ $cstatus='/';}else{if($v['cstatus']==1 && $q['lyrics'] == ''){$cstatus+=1;}}
                if($v['ystatus']==0){ $ystatus='/';}else{if($v['ystatus']==1 && $q['music_file_uuid'] != ''){ $ystatus+=1;}}
                if($v['bstatus']==0){ $bstatus='/';}else{if($v['bstatus']==1 && $q['accompaniment_file_uuid'] != ''){ $bstatus+=1;}}
                if($v['mstatus']==0){ $mstatus='/';}else{if($v['mstatus']==1 && $q['mv_file_uuid'] != ''){ $mstatus+=1;}}
                if($v['kstatus']==0){ $kstatus='/';}else{if($v['kstatus']==1 && $q['karaoke_file_uuid'] != ''){ $kstatus+=1;}}
                if($v['dstatus']==0){ $dstatus='/';}else{if($v['dstatus']==1 && $q['video_file_uuid'] != ''){ $dstatus+=1;}}
                $arrId[] = $q['id'];
                //改变文件的状态为更新授权书做准备
                Files::where('uuid', '=', $q['music_file_uuid'])->update(['check_status' => 1]);
                !empty($q['accompaniment_file_uuid']) && Files::where('uuid', '=', $q['accompaniment_file_uuid'])->update(['check_status' => 1]);
                !empty($q['mv_file_uuid']) && Files::where('uuid', '=', $q['mv_file_uuid'])->update(['check_status' => 1]);
                !empty($q['video_file_uuid']) && Files::where('uuid', '=', $q['video_file_uuid'])->update(['check_status' => 1]);
                !empty($q['karaoke_file_uuid']) && Files::where('uuid', '=', $q['karaoke_file_uuid'])->update(['check_status' => 1]);
            }
            $arr[$k]['simple_name'] = $v['simple_name'];
            $arr[$k]['cstatus'] = $cstatus;
            $arr[$k]['ystatus'] = $ystatus;
            $arr[$k]['bstatus'] = $bstatus;
            $arr[$k]['mstatus'] = $mstatus;
            $arr[$k]['kstatus'] = $kstatus;
            $arr[$k]['dstatus'] = $dstatus;
            if($v['cstatus']!=0 && $v['ystatus']!=0){
                $arr[$k]['total1'] = $cstatus+$ystatus;
            }else{
                $arr[$k]['total1'] = '/';
            }
            $arr[$k]['total2'] = 0;
            $cstatus!='/' &&  $arr[$k]['total2']+=$cstatus;
            $ystatus!='/' &&  $arr[$k]['total2']+=$ystatus;
            $bstatus!='/' &&  $arr[$k]['total2']+=$bstatus;
            $mstatus!='/' &&  $arr[$k]['total2']+=$mstatus;
            $kstatus!='/' &&  $arr[$k]['total2']+=$kstatus;
            $dstatus!='/' &&  $arr[$k]['total2']+=$dstatus;
        }
        return auto_return($arr,'返回成功');
    }

    //修改sp
    public function updateSp($data){
        $res = Sp::where('id','=',$data['id'])->update($data);
        return auto_return($res,'成功!');
    }

    //筛选出平台type为0正常上线其他为特殊上线
    public function selectSp($type){
        if($type == 0) {
            $sp = Sp::where('status','=',1)->select('id', 'full_name', 'simple_name', 'expired_time', 'cstatus', 'ystatus', 'bstatus', 'mstatus', 'kstatus', 'dstatus','fix_date','sp_email')->get()->toArray();
        }else{
            $music = Music::with('music_check')->where('type_status','=',$type)->where('check_status','=',2)->get()->toArray();
            foreach($music as $v){
                $simple_name[]=$v['music_check']['first_sp'];
            }
            $sp = Sp::whereIn('simple_name',$simple_name)->select('id', 'full_name', 'simple_name', 'expired_time', 'cstatus', 'ystatus', 'bstatus', 'mstatus', 'kstatus', 'dstatus','fix_date','sp_email')->get()->toArray();
        }
        return $sp;
    }

    //音乐发向平台生成对应材料
    public function musicToSp($data){
        //更改对应公司
        if(empty($data['company_id'])!=1 && !empty($data['company_id'])){
            Music::where('check_status', '=', 2)->where('type_status', '=', $data['type'])->update(['company_id'=>$data['company_id']]);
        }
        $sp = $this->selectSp($data['type']);
        $rand = rand_string(4);
        //得到对应平台的歌曲
        foreach($sp as $v) {
            if($data['type'] == 0) {
                $query = Music::where('check_status', '=', 2)->where('type_status', '=', $data['type'])->with('company', 'music_check', 'mv_file','music_file','accompaniment_file','video_file','karaoke_file')->whereHas('music_sp', function ($query) use ($v) {
                    $query->where('sp_id', '=', $v['id'])->where('status', '=', 1);
                });
                //筛选库
                if($data['library']!=1){
                    $library = json_decode($data['library']);
                    $query->whereHas('music_check', function ($query) use ($library) {
                        $query->whereIn('library',$library );
                    });
                }
                $query = $query->get()->toArray();
            }else{
                $query = Music::where('check_status', '=', 2)->where('type_status', '=', $data['type'])->with('company', 'music_check', 'mv_file','accompaniment_file','mv_file','video_file','karaoke_file')->whereHas('music_check', function ($query) use ($v) {
                    $query->where('first_sp', '=', $v['simple_name']);
                })->get()->toArray();
            }
            if(!empty($query)){
                $company_image = $query['0']['company']['company_image'];
                //生成带印章pdf
                $signPath = Office::instance()->makeSignPdf($query,$v['full_name'],$v['simple_name'],$v['expired_time'],$rand,$company_image, $v['fix_date'],$v['sp_email'],$data['onlineTime']);
                //生成无印章pdf
                $nosignPath = Office::instance()->makePdf($query,$v['full_name'],$v['simple_name'],$v['expired_time'],$rand, $v['fix_date'],$v['sp_email'],$data['onlineTime']);
                //生成execl
                if(!in_array($v['simple_name'],config('sp.sp'))) {
                    Office::instance()->makeExecl($query, $v['full_name'], $v['simple_name'], $v['fix_date'], $v['expired_time'], $rand,$data['onlineTime']);
                }
               //压缩pdf用于下载
                Office::instance()->makeFileZip($signPath,$nosignPath);
                //下载oss图片
                $res = Office::instance()->ossLoad($query);
                if($res != 200){
                    return auto_failure(['失败'],'下载oss资源失败');
                }
            }
        }
        //记录生成文件的位置
        DB::beginTransaction();
        try {
            $res1 = PdfFile::insert(['name' => $signPath, 'type' => 1]);
            $res2 = PdfFile::insert(['name' => $nosignPath]);
            $res3 = Files::where('check_status', '=', 1)->update(['sign' => $signPath, 'nosign' => $nosignPath]);
            //更新对应的上线时间
            $query = Music::where('check_status', '=', 2)->where('type_status', '=', $data['type']);
            if ($data['library'] != 1) {
                $library = json_decode($data['library']);
                $query->whereHas('music_check', function ($query) use ($library) {
                    $query->whereIn('library', $library);
                });
            }
            $query = $query->update(['online_time' => $data['onlineTime']]);
        }catch(\Exception $e){
               DB::rollback();
               return server_err(null, '数据库异常:' . $e->getMessage());
        }
        if ($res1 && $res2 && $res3) {
            DB::commit();
            return auto_return(['成功'],'添加成功！');
        } else {
            DB::rollBack();
            return auto_failure(['失败']);
        }
    }

    //发送邮件
    public static function sendMail($type,$library){
        $sp = (new MusicLogic())->selectSp($type);
        $rand = rand_string(4);
        $library = json_decode($library);
        foreach($sp as $v) {
            if($type == 0) {
                //单曲文件
                $query = Music::where('check_status', '=', 2)->where('album','=','')->with('company', 'music_check', 'music_file', 'accompaniment_file', 'mv_file', 'video_file', 'karaoke_file')->whereHas('music_sp', function ($query) use ($v) {
                    $query->where('sp_id', '=', $v['id'])->where('status', '=', 1);
                });
                if($library!=1){
                    $query->whereHas('music_check', function ($query) use ($library) {
                        $query->whereIn('library',$library );
                    });
                }
                $query = $query->get()->toArray();
                //专辑文件
                $album = Music::where('check_status', '=', 2)->where('album','<>','')->distinct()->select('album')->whereHas('music_sp', function ($query) use ($v) {
                    $query->where('sp_id', '=', $v['id'])->where('status', '=', 1);
                });
                if($library!=1){
                    $album->whereHas('music_check', function ($query) use ($library) {
                        $query->whereIn('library',$library );
                    });
                }
                $album = $album->get()->toArray();
            }else{
                //单曲
                $query = Music::where('check_status', '=', 2)->where('album','=','')->where('type_status', '=', $type)->with('company', 'music_check', 'music_file', 'accompaniment_file', 'mv_file', 'video_file', 'karaoke_file')->whereHas('music_check', function ($query) use ($v) {
                    $query->where('first_sp', '=', $v['simple_name']);
                })->get()->toArray();
                //专辑
                $album = Music::where('check_status', '=', 2)->where('type_status', '=', $type)->where('album','<>','')->distinct()->select('album')->whereHas('music_check', function ($query) use ($v) {
                    $query->where('first_sp', '=', $v['simple_name']);
                })->get()->toArray();
            }
            if(!empty($query) || !empty($album)) {
                //生成压缩文件并上传到oss上
                $ossUrl = Office::instance()->makeMusicZip($query, $v['simple_name'], $v['cstatus'], $v['ystatus'], $v['bstatus'], $v['mstatus'], $v['kstatus'], $v['dstatus'], $rand, $album, $type);
                if($ossUrl['code'] != 200){
                    throw_exception($ossUrl['msg'], $ossUrl);
                }
                //发送邮件
                Office::instance()->send($query, $v['full_name'], $v['simple_name'], $ossUrl['url'], $album, $type);
            }
        }
        //更改音乐状态已上线
        $m = Music::where('check_status', '=', 2)->where('type_status', '=', $type)->update(['check_status'=>4]);
        $res3 = Files::where('check_status', '=', 1)->update(['check_status' => 2]);
        if($m && $res3){
            return auto_return($m,'成功!');
        }else{
            return auto_failure($m,'操作失败');
        }

    }

    //独家发布
    public function musicToSingle($data){
        $id = explode(',',$data['id']);
        if($data['type']!=3){
            if($data['type'] == 1) {
                $end = date("Y-m-d", strtotime("+" . $data['first_time'] . " day", strtotime($data['start_time'])));
            }else {
                $end = date("Y-m-d", strtotime("+" . $data['first_time'] . " year", strtotime($data['start_time'])));
            }
            $res = MusicCheck::whereIn('music_id', $id)->update(['first_area' => $data['first_area'], 'first_sp' => $data['first_sp'], 'first_time' => $data['first_time'], 'start_time' => $data['start_time'], 'end_time' => $end]);
        }
        Music::whereIn('id',$id)->update(['type_status' => $data['type']]);
        return $this->singleList($data['type']);
    }

    //返回独家列表
    public function singleList($type){
        $res = Music::with('users_info','user','music_check')->where('check_status','=',2)->where('type_status','=',$type)->get()->toArray();
        return auto_return($res,'成功!');
    }
   
}